package cn.touna.jss.common.mail;

import cn.touna.jss.common.properties.config.MailProperties;
import cn.touna.jss.common.util.JssConstant;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 邮件发送工具
 * Created by Steve.Tao on 2017/11/6.
 */
@Service
public class MailComponent {

    private String host;

    public MailComponent(){
        restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(20000);
        requestFactory.setConnectTimeout(2000);
        restTemplate.setRequestFactory(requestFactory);

        try {
            host = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            logger.error("【MailComponent初始化】获取本机IP失败");
        }
    }

    private RestTemplate restTemplate;

    @Autowired
    private MailProperties mailProperties;

    private static  final Logger logger = LogManager.getLogger(MailComponent.class);

    /**
     * 发送邮件
     * @param title 标题
     * @param body 内容
     */
    public void send(String title,String body){
        if(mailProperties.isEnable()){
            send(mailProperties.getMailUrl(),title,body,mailProperties.getTo(),mailProperties.getCc(), JssConstant.SYSTEM_CODE);
        }else{
            logger.info("发送邮件被禁用");
        }
    }

    private void send(String url,String title,String body,String to,String cc,String callFrom){
        if(!mailProperties.isEnable()){
            logger.info("【发送邮件】功能被禁用");
            return;
        }
        if(StringUtils.isEmpty(url)){
            logger.info("【发送邮件】发送失败，mailUrl为空");
            return;
        }
        try{
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
            map.add("subject",title);
            map.add("mailBody",body);
            map.add("to",to);
            map.add("cc",cc);
            map.add("callFrom",callFrom);
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
            String str = restTemplate.postForObject(url,request,String.class);
            JSONObject res = JSONObject.parseObject(str);
            if(res.getInteger("code") != 1){
                logger.error("【发送邮件】发送失败,message:{}",res.getString("message"));
            }
        }catch (Exception e){
            logger.error("【发送邮件】发送失败,message:{}",e);
        }
    }
}
